/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servidorped.NetworkManager;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Micosil
 */
public class NetworkSender {
    private final Object Lock = new Object();
   
    BufferedOutputStream sout = null;
    boolean stuffToBeSent = false;

    public NetworkSender(Socket socket) throws IOException {     
        Logger.getLogger(NetworkSender.class.getName()).addHandler(new ConsoleHandler());
        try {
            sout = new BufferedOutputStream(socket.getOutputStream());
        } catch (IOException ex) {
            Logger.getLogger(NetworkSender.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }
    }       
    
    public boolean setToSendln(String message){        
        return(setToSend(message+"\n\r"));
    }
    
    public boolean sendAll(){
        try {
            sout.flush();
            return true;
        } catch (IOException ex) {
            Logger.getLogger(NetworkSender.class.getName()).log(Level.SEVERE, null, ex);
            try {
                this.sout.close();
            } catch (IOException ex1) {                
            }
            return false;
        }
        
    }
    
    public boolean thereIsStuffToSend(){
        return stuffToBeSent;        
    }

    public boolean setToSend(String message) {                        
        message = message.replace(";", "/;");
        message = message.concat(";");
        byte[] byteArray = message.getBytes();
        try {
            synchronized(Lock){
            sout.write(byteArray);            
            }
        } catch (IOException ex) {
            Logger.getGlobal().log(Level.SEVERE, null, ex);
            return false;
        }
        stuffToBeSent = true;

        return true;
    }
}
